package com.kason.service.user;

import com.kason.entity.Role;
import com.kason.entity.User;
import com.kason.repository.RoleRepository;
import com.kason.repository.UserRepository;
import com.kason.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by IBM on 2018/6/30.
 */
@Service
public class UserServiceImpl implements IUserService {


    @Autowired
    UserRepository userRepository;
    @Autowired
    RoleRepository roleRepository;
    @Override
    public User findUserByName(String userName) {
        User user = userRepository.findUserByName(userName);
        if (null == user) {
            return null;
        }
        List<Role> rolesByUserId = roleRepository.findRolesByUserId(user.getId());
        if (null == rolesByUserId) {
            throw new DisabledException("no role");
        }
        List<GrantedAuthority> authorities = new ArrayList<>();
        rolesByUserId.forEach(role -> authorities.add(new SimpleGrantedAuthority("ROLE_" + role.getName())));
        user.setAuthorityList(authorities);

        return user;
    }
}
